// pages/user_management/user_management.js
let listBehavior = require('../../behavior/list')

Page({
  behaviors: [ listBehavior, ],
  /**
   * 页面的初始数据
   */
  data: {
    auth: {},

    limit: 10,

    quickFlag: false,
    searchList: [
      { field_name: '角色', type: 'reference1', field_id: 'role_id', optionList: [], optionId: 'id', optionName: 'name', },
      { field_name: '录入时间', type: 'date', field_id: 'input_time', },
    ],
    searchWhere: [],
    searchVal: '',
  },

  navTo(e) {
    let { item, } = e.currentTarget.dataset,
        { auth, } = this.data,
        url = '../user_management_add/user_management_add?entity=all_user',
        msg = !auth.tableAppend ? '抱歉，您没有权限新增该模块数据' : ''
    if(item && item.user_id) {
      url += `&id=${item.user_id}`
      if(!auth.tableEdit) msg = '抱歉，您没有权限编辑该模块数据'
    }
    if(msg) {
      wx.$toast(msg)
      return
    }
    wx.navigateTo({
      url,
    })
  },

  toggleFlag(e) {
    this.setData({
      quickFlag: !this.data.quickFlag,
    })
  },
  searchQuick(e) {
    let searchWhere = e.detail,
        { searchList, } = this.data,
        arr = [],
        searchObj = {}
    searchWhere.forEach(item => {
      let fieldId = item.CompareWith,
          field = searchList.filter(field => field.field_id === fieldId)[0],
          name = field.field_name,
          type = field.type,
          val = item.CompareValue
      if(type === 'date') {
        if(!searchObj[name]) searchObj[name] = []
        searchObj[name].push(val)
      } else if(type === 'reference1') {
        let optName = field.optionList.filter(opt => val === opt[field.optionId])[0][field.optionName]
        searchObj[name] = optName
      } else {
        searchObj[name] = val
      }
    })
    Object.entries(searchObj).forEach(([key, val]) => {
      val = Array.isArray(val) ? val.join('-') : val
      arr.push(`${key}：${val}`)
    })
    this.setData({
      searchVal: arr.join('，'),
      searchWhere,
    })
    this.getFirstPage()
  },
  delData(e) {
    let { item, } = e.currentTarget.dataset
    console.log(item);
    wx.showModal({
      // title: '确认退出登录？',
      content: '确认删除该条数据？',
      success: (res) => {
        if(res.confirm) this.delUserData(item.user_id)
      },
    })
  },

  // 接口
  ready() {
    // 获取角色列表
    let p0 = this.getOptionList(1, 'role_id', 3, 'BaseTable/select_role', {})

    Promise.all([p0]).then(res => {
      let searchList = this.data.searchList,
          obj = {}
      res.forEach((item, i) => {
        obj = { ...obj, ...item, }
      })
      searchList.forEach(item => {
        let key = item.field_id
        if(obj[key]) item.optionList = obj[key]
      })
      this.setData({
        searchList,
      })
    })
  },
  getOptionList() {
    return new Promise((resolve, reject) => {
      let [ method, key, v, url, params, ] = arguments
      let request = method ? wx.$get : wx.$post
      request(v, url, params).then(res => {
        if(res.errcode !== 0) return
        let rows = res.data.row
        rows = rows.flat()
        resolve({ [key]: rows, })
      })
    })
  },
  // 获取列表
  getDataList() {
    if(!this.data.auth.tableSee) {
      let { total, page, limit, } = this.data
      wx.$toast('抱歉，您没有权限查看该模块')
      this.setData({
        total,
        page,
        limit,
      })
      return
    }

    let { page, limit, list, searchWhere, } = this.data,
        post = {
          oby: 'input_time desc',
          page,
          limit,
          // SearchWhere: {
          //   type: 'and',
          //   filters: searchWhere,
          //   children: [],
          // },
        }

    if(searchWhere.length) post.SearchWhere = searchWhere

    wx.$post(3, 'BaseTable/query_all_user', post).then(res => {
      if(res.errcode !== 0) return
      let rows = res.data.row
      if(page !== 1) rows = [ ...list, ...rows, ]
      this.setData({
        list: rows,
        total: res.data.total,
        page,
      })
    })
  },
  delUserData(userId) {
    let post = {
      system_id: 800,
      user_id: userId,
    }
    wx.showLoading({ mask: true, })
    wx.$post(3, 'BaseTable/del_user', post).then(res => {
      if(res.errcode !== 0) return
      wx.$toast('删除成功！')
      this.getFirstPage()
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.$setBarTitle();
    let { entity, } = options
    this.entity = entity
    this.ready()
    // this.getDataList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    if(this.data.auth.tableSee === undefined) {
      this.data.auth = await wx.$getAuth(this.entity)
    }
    if(!this.data.total) {
      this.getDataList()
    } else {
      this.getFirstPage()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
})
